package src.array;

import java.util.Arrays;

public class no977 {
//有序数组的平方
    public static void main(String[] args) {

        int[] nums = {-7,-3,2,3,11};
//        for (int result: sortedSquares(nums)) {
//            System.out.print(result+" ");
        int[] result = sortedSquares2(nums);
        System.out.println(Arrays.toString(result));
        }

    public static int[] sortedSquares1(int[] nums) {

//        int light = 0;
//        int right = nums.length - 1;
        int k = nums.length - 1;
        int[] result = new int[nums.length];

        for (int i = 0, j = nums.length - 1; i < j; ) {
            if (nums[i] * nums[i] > nums[j] * nums[j]) {
                result[k] = nums[i] * nums[i];
                k--;
                i++;
            } else {
                result[k] = nums[j] * nums[j];
                k--;
                j--;
            }
        }

        return result;
    }

    public static int[] sortedSquares2(int[] nums) {
        int l = 0;
        int r = nums.length - 1;
        int[] res = new int[nums.length];
        int j = nums.length - 1;
        while(l <= r){
            if(nums[l] * nums[l] > nums[r] * nums[r]){
                res[j] = nums[l] * nums[l];
                j--;
                l++;
            }else{
                res[j] = nums[r] * nums[r];
                j--;
                r--;
            }
        }
        return res;
    }

}
